<template>
  <div class="积分商城-container">
    <!-- 顶部标题栏 -->
    <el-container class="header-container">
      <el-header style="background-color: #f5f5f5; padding: 0 20px;">
        <el-row :gutter="20" style="height: 60px; align-items: center;">
          <!-- 居中标题 -->
          <el-col :span="17" :offset="3" style="text-align: center;">
            <h1 style="font-size: 24px; color: #35984b; margin: 0;">积分商城</h1>
          </el-col>
          <el-col :span="4" style="float: right;">
            <h4 style="color: #666666;">当前积分：{{ user.points }}</h4>
          </el-col>
        </el-row>
      </el-header>
    </el-container>

    <!-- 筛选和排序 -->
    <el-container class="filter-container">
      <el-main>
        <el-row>
          <el-col :span="10" :offset="2">
            <el-select v-model="selectedCategory" placeholder="选择分类" style="width: 400px;">
              <el-option label="全部" value="all"></el-option>
              <el-option label="家居用品" value="home"></el-option>
              <el-option label="环保产品" value="eco"></el-option>
              <el-option label="书籍资料" value="book"></el-option>
              <el-option label="服务权益" value="service"></el-option>
              <el-option label="电子产品" value="electronic_products"></el-option>
              <el-option label="低碳生活" value="low_carbon"></el-option>
              <el-option label="健康生活" value="health_life"></el-option>
              <el-option label="美食体验" value="food_experience"></el-option>
            </el-select>
          </el-col>
          <el-col :span="10" style="width: 400px;" >
            <el-select v-model="sortType" placeholder="排序方式">
              <el-option label="积分从低到高" value="asc"></el-option>
              <el-option label="积分从高到低" value="desc"></el-option>
              <el-option label="最新上架" value="newest"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 商品列表 -->
    <el-container class="goods-list-container">
      <el-main>
        <el-row :gutter="24" v-if="sortedGoodsList.length > 0">
          <el-col :span="6" v-for="item in sortedGoodsList" :key="item.id">
            <el-card class="goods-card">
              <div class="goods-image-wrap">
                <img :src="item.imageUrl" alt="商品图片" class="goods-image">
                <!-- 分类标签 -->
                <div class="category-label" :style="{ backgroundColor: getCategoryColor(item.category) }">
                  {{ item.category | categoryFilter }}
                </div>
              </div>
              <div class="goods-info">
                <h3 class="goods-name">{{ item.name }}</h3>
                <p class="points-needed">
                  <el-icon class="points-icon"><CoinFilled/></el-icon>
                  {{ item.points }} 积分
                </p>
                <p class="goods-desc" :title="item.description">
                  {{ item.description.slice(0, 35) }}...
                </p>
                <el-button
                    type="success"
                    @click="handleExchange(item.id)"
                    class="exchange-btn"
                >
                  去兑换
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 空状态提示 -->
        <div class="empty-state" v-else>
          <el-icon style="font-size: 48px; color: #c1c1c1;"><GiftFilled/></el-icon>
          <p style="font-size: 16px; color: #606266;">没有找到匹配的商品</p>
        </div>
      </el-main>
    </el-container>

    <!-- 商品详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="currentGoods.name"
        width="50%"
        :close-on-click-modal="false"
        class="goods-detail-dialog"
    >
      <el-row :gutter="30">
        <!-- 图片区域 -->
        <el-col :span="12">
          <div class="goods-image-container">
            <div class="goods-image-wrapper">
              <img
                  :src="currentGoods.imageUrl"
                  :alt="currentGoods.name"
                  class="detail-goods-image"
              >
              <div
                  class="category-label"
                  :style="{ backgroundColor: getCategoryColor(currentGoods.category) }"
              >
                {{ currentGoods.category | categoryFilter }}
              </div>
            </div>
          </div>
        </el-col>

        <!-- 信息区域 -->
        <el-col :span="12">
          <div class="goods-detail-content">
            <h2 class="detail-goods-name">{{ currentGoods.name }}</h2>

            <div class="points-display">
              <el-icon class="points-icon"><CoinFilled /></el-icon>
              <span class="points-value">{{ currentGoods.points }}</span>
              <span class="points-text">积分/件</span>
            </div>

            <div class="goods-description">
              <h4>商品描述</h4>
              <p>{{ currentGoods.description }}</p>
            </div>

            <el-form class="exchange-form">
              <el-form-item label="兑换数量" class="quantity-item">
                <el-input-number
                    v-model="exchangeQuantity"
                    :min="1"
                    :max="10"
                    controls-position="right"
                    size="large"
                />
              </el-form-item>

              <el-form-item label="总需积分" class="total-points-item">
                <div class="total-points-display">
                  <el-icon class="total-points-icon"><CoinFilled /></el-icon>
                  <span class="total-points-value">{{ currentGoods.points * exchangeQuantity }}</span>
                  <span class="total-points-text">积分</span>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button
              type="info"
              @click="detailDialogVisible = false"
              class="cancel-btn"
          >
            取消
          </el-button>
          <el-button
              type="success"
              @click="handleConfirmExchange"
              class="confirm-btn"
          >
            确认兑换
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import axios from "axios";
import qs from "qs";

const router = useRouter();
const goodsList = ref([
  // 书籍资料类
  {
    id: 1,
    name: '垃圾分类指导手册',
    points: 50,
    description: '涵盖垃圾分类、物品循环利用、低碳饮食等实用技巧，附手绘插图',
    imageUrl: './imgs/record/垃圾分类指导手册.png',
    category: 'book'
  },
  {
    id: 2,
    name: '环保知识线上课程',
    points: 100,
    description: '4节视频课（每节30分钟），包含废弃物管理、可持续消费等内容，永久回看',
    imageUrl: './imgs/record/环保知识线上课程.png',
    category: 'book'
  },

  // 环保产品类
  {
    id: 3,
    name: '可折叠硅胶水杯',
    points: 300,
    description: '食品级硅胶材质，折叠后仅3cm厚，携带方便，减少一次性杯使用',
    imageUrl: './imgs/record/可折叠硅胶水杯.png',
    category: 'eco'
  },
  {
    id: 4,
    name: '竹纤维洗碗布（3片装）',
    points: 60,
    description: '天然竹纤维制成，可降解，去污力强，替代传统海绵',
    imageUrl: './imgs/record/竹纤维洗碗布.png',
    category: 'eco'
  },
  {
    id: 5,
    name: '太阳能小夜灯',
    points: 333,
    description: '白天太阳能充电，夜间自动亮灯，适合阳台或庭院，节能又美观',
    imageUrl: './imgs/record/太阳能小夜灯.png',
    category: 'eco'
  },
  {
    id: 17,
    name: '环保餐具套装（含筷子、勺子、叉子）',
    points: 222,
    description: '采用可降解材料制成的环保餐具套装，安全无毒，设计精美，方便携带，适合外出就餐或野餐时使用，减少一次性餐具的使用',
    imageUrl: './imgs/record/环保餐具套装.png',
    category: 'eco'
  },

  // 家居用品类
  {
    id: 6,
    name: '厨房食物残渣堆肥桶',
    points: 700,
    description: '5L容量，带活性炭过滤层，可将厨余转化为肥料，适合家庭阳台使用',
    imageUrl: './imgs/record/堆肥桶.png',
    category: 'home'
  },
  {
    id: 7,
    name: '环保购物袋（2只装）',
    points: 150,
    description: '承重5kg，印有环保标语，可机洗重复使用',
    imageUrl: './imgs/record/环保购物袋.png',
    category: 'home'
  },
  {
    id: 8,
    name: '智能感应垃圾桶',
    points: 2000,
    description: '12L容量，挥手感应开盖，内置垃圾袋固定环，支持干湿垃圾分类',
    imageUrl: './imgs/record/垃圾桶.png',
    category: 'home'
  },

  // 服务权益类
  {
    id: 9,
    name: '有害垃圾上门回收服务',
    points: 600,
    description: '预约后48小时内上门收取电池、过期药品、荧光灯管等有害垃圾，专业处理',
    imageUrl: './imgs/record/回收服务.png',
    category: 'service'
  },
  {
    id: 11,
    name: '环保志愿者证书',
    points: 300,
    description: '参与满2次社区环保活动后可兑换，电子版证书可用于社会实践证明',
    imageUrl: './imgs/record/证书.png',
    category: 'service'
  },

  // 电子产品类
  {
    id: 10,
    name: 'iPhone 15',
    points: 1500000,
    description: '全新iPhone 15',
    imageUrl: './imgs/record/手机.png',
    category: 'electronic_products'
  },
  {
    id: 15,
    name: '智能手环',
    points: 15000,
    description: '具有心率监测、运动记录、睡眠监测等功能的智能手环，支持蓝牙连接手机，续航长达7天',
    imageUrl: './imgs/record/智能手环.png',
    category: 'electronic_products'
  },

  // 健康生活类
  {
    id: 12,
    name: '瑜伽垫',
    points: 400,
    description: '环保TPE材质瑜伽垫，厚度6mm，防滑耐磨，尺寸为183cm×61cm，适合各种瑜伽练习和家庭健身',
    imageUrl: './imgs/record/瑜伽垫.png',
    category: 'health_life'
  },
  {
    id: 13,
    name: '运动水壶',
    points: 450,
    description: '运动水壶，容量500ml，一键开盖，携带方便，适合户外运动时保持水分',
    imageUrl: './imgs/record/运动水壶.png',
    category: 'health_life'
  },

  // 低碳生活类
  {
    id: 14,
    name: '低碳出行优惠券包',
    points: 290,
    description: '包含共享单车5折券3张、打车六折优惠券2张，有效期30天',
    imageUrl: './imgs/record/优惠券.png',
    category: 'low_carbon'
  },

  // 美食体验类
  {
    id: 16,
    name: '有机蔬菜礼盒',
    points: 510,
    description: '精选当季有机蔬菜，无农药残留，新鲜直达，包含多种蔬菜品种，满足家庭一周的蔬菜需求，享受健康美味的有机生活',
    imageUrl: './imgs/record/有机蔬菜礼盒.png',
    category: 'food_experience'
  },
  {
    id: 18,
    name: '咖啡渣手工皂',
    points: 350,
    description: '由咖啡渣和天然植物油制成的手工皂，具有温和的清洁力和去角质功能，同时散发着浓郁的咖啡香气，为您带来独特的沐浴体验',
    imageUrl: './imgs/record/咖啡渣手工皂.png',
    category: 'food_experience'
  },

  // 亲子互动类
  {
    id: 19,
    name: '环保手工包',
    points: 250,
    description: '包含各种环保材料和工具，如废旧纸盒、彩色卡纸、剪刀、胶水等，以及详细的手工教程，适合家长和孩子一起动手制作环保手工艺品，增进亲子关系',
    imageUrl: './imgs/record/环保手工包.png',
    category: 'eco'
  },
  {
    id: 20,
    name: '幼儿科普环保绘本',
    points: 180,
    description: '一本以环保为主题的儿童绘本，通过生动有趣的故事和精美的插画，向孩子们传递环保知识和理念，培养他们的环保意识',
    imageUrl: './imgs/record/幼儿绘本.png',
    category: 'book'
  },
]);

const dialogVisible = ref(false);
const dialogMessage = ref('');
const dialogType = ref('');
const detailDialogVisible = ref(false);
const currentGoods = ref({});
const exchangeQuantity = ref(1);

const user = ref(getUser());

// 兑换确认逻辑
const handleConfirmExchange = async () => {
  const totalPoints = currentGoods.value.points * exchangeQuantity.value;

  if (totalPoints > user.value.points) {
    ElMessage.warning('积分不足，无法兑换');
    return;
  }

  try {
    // 扣除积分并提交到后端
    const newPoints = user.value.points - totalPoints;
    let data = qs.stringify({
      points: newPoints,
      id: user.value.id
    });

    const response = await axios.post('http://localhost:8080/v1/user/savePoints', data);

    if (response.data && response.data.code === 2000) {
      ElMessage.success('兑换成功');
      user.value.points = newPoints; // 更新当前用户的积分
      detailDialogVisible.value = false;
    } else {
      ElMessage.error(response.data?.msg || '兑换失败');
    }
  } catch (error) {
    console.error('兑换失败:', error);
    ElMessage.error('兑换请求失败，请稍后重试');
  }
};

// 筛选和排序相关
const selectedCategory = ref('all');
const sortType = ref('asc'); // 默认按积分从低到高排序

// 计算属性：根据分类和排序方式过滤商品
const sortedGoodsList = computed(() => {
  // 先按分类过滤
  let filteredGoods = goodsList.value;
  if (selectedCategory.value !== 'all') {
    filteredGoods = goodsList.value.filter(item => item.category === selectedCategory.value);
  }

  // 再按排序方式排序
  return [...filteredGoods].sort((a, b) => {
    if (sortType.value === 'asc') {
      return a.points - b.points; // 积分从低到高
    } else if (sortType.value === 'desc') {
      return b.points - a.points; // 积分从高到低
    } else {
      return b.id - a.id; // 最新上架（ID降序）
    }
  });
});

// 分类颜色映射
const categoryColorMap = {
  book: '#e6a23c', // 书籍资料
  eco: '#299999', // 环保产品
  home: '#409eff', // 家居用品
  service: '#909399', // 服务权益
  low_carbon: '#19f469', // 低碳生活
  electronic_products: '#2d2ff0', // 电子产品
  health_life: '#4dbd74', // 健康生活
  food_experience: '#a7ba2a', // 美食体验
  parent_child: '#909eff', // 亲子互动
};

// 分类过滤器
const categoryFilter = (value) => {
  return {
    book: '书籍资料',
    eco: '环保产品',
    home: '家居用品',
    service: '服务权益',
    low_carbon: '低碳生活',
    electronic_products: '电子产品',
    health_life: '健康生活',
    food_experience: '美食体验',
  }[value] || '全部';
};

// 获取分类颜色
const getCategoryColor = (category) => {
  return categoryColorMap[category] || '#dcdfe6';
};


// 兑换逻辑
const handleExchange = (goodsId) => {
  const targetGoods = goodsList.value.find(item => item.id === goodsId);
  if (!targetGoods) {
    ElMessage.error('商品不存在');
    return;
  }

  currentGoods.value = targetGoods;
  exchangeQuantity.value = 1;
  detailDialogVisible.value = true;
};

const closeDialog = () => {
  dialogVisible.value = false;
};

const simulateExchange = (goodsId, quantity) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({code: 200, msg: '兑换成功'});
    }, 800);
  }).then(res => {
    if (res.code === 200) {
      dialogType.value = 'success';
      dialogMessage.value = `成功兑换${quantity}件商品！我们将尽快为您处理`;
      dialogVisible.value = true;

      // 更新积分
      const targetGoods = goodsList.value.find(item => item.id === goodsId);
      user.value.points -= targetGoods.points * quantity;
      localStorage.setItem('userPoints', user.value.points);
    } else {
      dialogType.value = 'error';
      dialogMessage.value = `兑换失败：${res.msg || '未知错误'}`;
      dialogVisible.value = true;
    }
  }).catch(err => {
    console.error('兑换失败:', err);
    dialogType.value = 'error';
    dialogMessage.value = '系统异常，兑换失败';
    dialogVisible.value = true;
  });
};

</script>

<style scoped>
/* 样式优化 */
.积分商城-container {
  min-height: calc(100vh - 160px);
  padding: 20px;
  background-color: #f8f9fa;
}

.header-container {
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.el-header {
  padding: 0 !important;
}

.filter-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}

.goods-card {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s;
}

.goods-card:hover {
  transform: translateY(-5px);
}

.goods-image-wrap {
  width: 100%;
  height: 200px;
  overflow: hidden;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.category-label {
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 2px 8px;
  font-size: 12px;
  color: white;
  border-radius: 10px;
  font-weight: 500;
}

.goods-image {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
  transition: transform 0.3s;
}

.goods-image:hover {
  transform: scale(1.05);
}

.goods-info {
  padding: 15px;
  text-align: center;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.points-needed {
  color: #e6a23c;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.points-icon {
  font-size: 18px;
}

.goods-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.exchange-btn {
  width: 100%;
  padding: 8px;
  border-radius: 4px;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.dialog-style {
  width: 350px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.dialog-style .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #f0f2f5;
}

.dialog-style .el-dialog__title {
  font-size: 18px;
  color: #303133;
}

.dialog-style .el-dialog__body {
  padding: 20px;
  text-align: center;
}

.goods-detail-info {
  padding: 0 20px;
}

.goods-detail-info h2 {
  font-size: 24px;
  margin-bottom: 15px;
  color: #333;
}

.goods-detail-info .goods-desc {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin: 20px 0;
}

.total-points {
  font-size: 18px;
  color: #e6a23c;
  font-weight: bold;
}
/* 商品详情弹窗样式 */
.goods-detail-dialog {
  border-radius: 12px;
}

.goods-detail-dialog .el-dialog__header {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f2f5;
}

.goods-detail-dialog .el-dialog__body {
  padding: 20px;
}

/* 图片容器 */
.goods-image-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.goods-image-wrapper {
  position: relative;
  width: 100%;
  height: 300px;
  background-color: #f8f8f8;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.detail-goods-image {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
}

/* 商品详情内容 */
.goods-detail-content {
  padding: 0 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-goods-name {
  font-size: 24px;
  margin: 0 0 15px 0;
  color: #333;
  line-height: 1.3;
}

/* 积分显示 */
.points-display {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.points-icon {
  font-size: 24px;
  color: #e6a23c;
  margin-right: 8px;
}

.points-value {
  font-size: 24px;
  font-weight: bold;
  color: #e6a23c;
  margin-right: 5px;
}

.points-text {
  font-size: 16px;
  color: #606266;
}

/* 商品描述 */
.goods-description {
  margin-bottom: 25px;
  flex-grow: 1;
}

.goods-description h4 {
  font-size: 16px;
  color: #909399;
  margin-bottom: 10px;
}

.goods-description p {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

/* 兑换表单 */
.exchange-form {
  margin-top: auto;
}

.quantity-item {
  margin-bottom: 15px;
}

.quantity-item .el-input-number {
  width: 120px;
}

.quantity-item .el-input-number__decrease,
.quantity-item .el-input-number__increase {
  background-color: #f5f7fa;
}

.total-points-item {
  margin-bottom: 0;
}

.total-points-display {
  display: flex;
  align-items: center;
  font-size: 18px;
}

.total-points-icon {
  font-size: 20px;
  color: #e6a23c;
  margin-right: 8px;
}

.total-points-value {
  font-weight: bold;
  color: #e6a23c;
  margin-right: 5px;
}

.total-points-text {
  color: #606266;
}

/* 弹窗底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
}

.cancel-btn {
  padding: 10px 20px;
}

.confirm-btn {
  padding: 10px 20px;
  margin-left: 15px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .goods-detail-dialog {
    width: 80% !important;
  }

  .goods-image-wrapper {
    height: 250px;
  }
}

@media (max-width: 768px) {
  .goods-detail-dialog {
    width: 90% !important;
  }

  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .goods-image-wrapper {
    height: 200px;
  }
}
</style>